package com.mzj.saas.sdk.withdraw.wx;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.net.ssl.SSLContext;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.mzj.saas.sdk.util.WechatUtils;
import com.mzj.saas.sdk.withdraw.vo.WxWithdraw;
import com.mzj.saas.sdk.withdraw.vo.WxWithdrawRes;

/**
 * 微信转账/提现
 * 
 * @author hp
 *
 */
public class WxTransfersRequest {

	private final static Logger logger = LoggerFactory.getLogger(WxTransfersRequest.class);

	private WxWithdraw wxWithdraw;

	public WxTransfersRequest(final WxWithdraw wxWithdraw){
		this.wxWithdraw = wxWithdraw;
	}

	/**
	 * 企业付款到零钱
	 * <p>
	 *  接口文档地址：https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2
	 * </p>
	 * 
	 * @return null为失败，成功则返回响应对象
	 */
	public WxWithdrawRes toTransfers() {
		
		WxWithdrawRes result = null;
		if(wxWithdraw == null) {
			logger.error("企业付款到零钱---------->wxWithdraw is null");
			return result;
		}
		try {
			SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
			parameters.put("mch_appid", wxWithdraw.getMchAppid());
			parameters.put("mchid", wxWithdraw.getMchId());
			parameters.put("partner_trade_no", wxWithdraw.getPartnerTradeNo());
			parameters.put("nonce_str", WechatUtils.generateNonceStr());
			parameters.put("openid", wxWithdraw.getOpenid());
			parameters.put("check_name", "FORCE_CHECK");
			parameters.put("re_user_name", wxWithdraw.getReUserName());
			parameters.put("amount", wxWithdraw.getAmount());
			parameters.put("desc", wxWithdraw.getDesc());
			
			String sign = WechatUtils.getSign("UTF-8", parameters, wxWithdraw.getMchApiKey());
			parameters.put("sign", sign);
			logger.info("WxTransfers toTransfers parameters = {}", JSONObject.toJSON(parameters));
			
			byte[] certP12 = wxWithdraw.getMchCertificate();
			char[] mchIdArray = wxWithdraw.getMchId().toString().toCharArray();
	        InputStream inputStream = new ByteArrayInputStream(certP12);
	        KeyStore keyStore = KeyStore.getInstance("PKCS12");
	        keyStore.load(inputStream, mchIdArray);
	        
	        if (inputStream != null) {
	            inputStream.close();
	        }
	        
	        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mchIdArray).build();
	        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"},
	                null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
	        HttpPost httpPost = new HttpPost(wxWithdraw.getTransfersUrl());
	        logger.info("WxTransfers toTransfers xml = {}", WechatUtils.mapToXml(parameters), "UTF-8");
	        httpPost.setEntity(new StringEntity(WechatUtils.mapToXml(parameters), "UTF-8"));
	        
	        // 加载含有证书的http请求
	        CloseableHttpResponse response = HttpClients.custom().setSSLSocketFactory(socketFactory).build().execute(httpPost);
	        String resultXml = EntityUtils.toString(response.getEntity(), "utf-8");
	        logger.info("WxTransfers toTransfers result = {}",resultXml);
	        
	        result =  WechatUtils.xmlToChangeRes(resultXml);
		}catch(Exception e) {
			logger.error("WxTransfers Service Exception = " + e,e.getMessage());
		}
		return result;
	}
}
